/*****目标团队--靶标 --攻防赛*****/
<template>
  <!---->
  <search-table
    ref="searchTable"
    :columns="targetTeamCol"
    :data="targetTeamData"
    :total="targetTeamTotal"
    :page.sync="queryTargetTeamInfo.pageIndex"
    :size.sync="queryTargetTeamInfo.pageSize"
    @change-size="getTargetSize"
    @change-page="getTargetPage"
  >
    <template slot="search">
      <!-- <Button  type='primary' ghost @click="showAddAndUpdate('')" :disabled="disabledAllBtn"><Icon type="ios-add" :size="16"/>添加题目</Button> -->
      <Select filterable
        v-model="queryTargetTeamInfo.type"
        placeholder="任务类型"
        @on-change="getTargetPage(1)"
        style="width: 150px"
        transfer
        clearable
      >
        <Option :value="1">虚拟机靶标</Option>
        <Option :value="2">分析靶标</Option>
      </Select>
      <!--<DatePicker format="yyyy-MM-dd HH:mm:ss" type="daterange"  placeholder="选择日期" style="width: 200px"
                        @on-change="searchTargetPrjD"></DatePicker>-->
      <!--<Input v-model.trim="searchPrjString" search placeholder="题目显示名称" style="width: 200px" @on-search="searchTargetPrj"  />-->
    </template>
    <Modal
      v-model="targetModal.show"
      :title="targetModal.title"
      :loading="targetModal.loading"
      width="600px"
      :mask-closable="false"
      @on-visible-change="visibleChange"
      @on-cancel="handleReset('formValidate')"
      @on-ok="saveTargetTeam"
    >
      <Form
        ref="formValidate"
        :model="formValidate"
        :rules="ruleValidate"
        :label-width="100"
      >
        <FormItem
          label="是否显示"
          prop="targetVisibility"
          v-if="[4].includes(type)"
          key="targetVisibility"
        >
          <RadioGroup v-model="formValidate.targetVisibility" @on-change="formValidate.timer = false;formValidate.showTime = ''">
            <Radio :label="1">是</Radio>
            <Radio :label="0">否</Radio>
          </RadioGroup>
        </FormItem>
        <Row
          v-if="[4].includes(type) && formValidate.targetVisibility === 0"
          key="timeDisplay"
        >
          <Col span="4">
            <FormItem label="定时显示">
              <Checkbox
                v-model="formValidate.timer"
                @on-change="setTime"
                style="line-height: 32px"
              ></Checkbox>
            </FormItem>
          </Col>
          <Col span="14">
            <FormItem label="显示时间：">
              <!--:options = "timeOptions"-->
              <DatePicker
                v-model="formValidate.showTime"
                placeholder="请选择显示时间"
                type="datetime"
                style="width: 200px"
                :editable="false"
                format="yyyy-MM-dd HH:mm"
                v-if="formValidate.timer"
                @on-change="changeTime($event)"
              ></DatePicker>
              <span class="error-text" v-show="showErrorText">{{
                errorText
              }}</span>
            </FormItem>
          </Col>
        </Row>
        <FormItem label="任务类型">
          <RadioGroup v-model="formValidate.type" @on-change="changeType">
            <Radio :label="1" :disabled="isUpdate">虚拟机靶标</Radio>
            <Radio :label="2" :disabled="isUpdate">分析靶标</Radio>
          </RadioGroup>
        </FormItem>
        <!--1:攻防赛，渗透演练需要题目-->
        <!-- <FormItem label="题目" prop="questionId">
            <Select filterable v-model="formValidate.questionId" placeholder="请选择题目" @on-change="setTeamQuestion" filterable :label-in-value="true"> 
                <Option  
                    v-for="question in showQuestionList" 
                    :value="question.id"  
                    :key="question.key">{{question.type == 'target' ? '[漏洞靶标库]':'[主观题题库]'}}{{question.name}}</Option>
            </Select>
        </FormItem> -->
        <FormItem label="题目显示名称" prop="name">
          <Input
            v-model.trim="formValidate.name"
            placeholder="题目显示名称"
          ></Input>
        </FormItem>
        <!--<FormItem label="靶标类型" prop="type" @on-change="formValidate.path == ''">
            <RadioGroup v-model="formValidate.type">
            <Radio :label=0>flag</Radio>
            <Radio :label=1>多个虚拟机flag相同</Radio>
            <Radio :label=2>多个虚拟机flag不同</Radio>
            <Radio :label=3 >文档</Radio>
            </RadioGroup>
        </FormItem>-->
        <!--<FormItem label="所属团队" prop="teamId">
            <Select filterable  v-model="formValidate.teamId" placeholder="请选择团队" @on-change="changeTeamGroup">
            <Option  v-for="item in accessGroupList" :value="item.id"  :key="item.id">{{item.name}}</Option>
            </Select>
        </FormItem>
        <FormItem label="子网" prop="subnet">
            <Select filterable  v-model="formValidate.subnet" placeholder="请选择子网" @on-change="changeSubnet">
            <Option  v-for="item in subnetList" :value="item.id"  :key="item.id">{{item.name}}</Option>
            </Select>
        </FormItem>
        <FormItem label="虚拟机" prop="vmId" v-show="formValidate.questionId">
            <Select filterable v-model="formValidate.vmId" placeholder="请选择虚拟机" filterable @on-change="changeVm" ref="vmSelect">
            <Option v-for="item in vmlists" :value="item.id" :key="item.id">{{item.name}}</Option>
            </Select>
        </FormItem>-->
        <FormItem label="分值" prop="score">
          <InputNumber
            :min="0"
            :max="1000"
            v-model="formValidate.score"
            placeholder="请输入分值"
          ></InputNumber>
          <span style="color: #f90">
            <Icon type="ios-information-circle-outline" />
            本靶标的基础分
          </span>
        </FormItem>
        <!--<FormItem  label="是否显示" prop="visibility">
            <RadioGroup v-model="formValidate.visibility">
            <Radio :label=1>显示</Radio>
            <Radio :label=0>不显示</Radio>
            </RadioGroup>
            <span style="color:#f90"> <Icon type="ios-information-circle-outline" />用于在演练页面的展示控制</span>
        </FormItem>-->
        <!--渗透需要题目顺序-->
        <FormItem label="排序" prop="sequence" v-if="type == 4 && stMode == 0">
          <InputNumber
            v-model="formValidate.sequence"
            :min="1"
            placeholder="请输入排序"
          ></InputNumber>
        </FormItem>
        <FormItem
          label="Flag路径"
          prop="flagPath"
          v-if="formValidate.type !== 2"
        >
          <Input
            v-model.trim="formValidate.flagPath"
            placeholder="请输入路径"
          ></Input>
        </FormItem>
        <FormItem
          label="Flag"
          prop="flag"
          v-if="formValidate.type === 2 && formValidate.isFixedFileFlag == '1'"
        >
          <Input
            v-model.trim="formValidate.flag"
            placeholder="请输入flag"
            disabled
          ></Input>
        </FormItem>
        <!--<FormItem label="flag路径" prop="path" v-if="formValidate.type == 0 && pathList.length > 0">
            <Select filterable v-model="formValidate.path" placeholder="请输入路径">
            <Option v-for="path in pathList" :value="path.addresses[0].applyFlagUrl" :key="path.id">{{path.addresses[0].applyFlagUrl}}</Option>
            </Select>
        </FormItem>-->
        <!--<FormItem  label="访问方式" prop="access">
            <RadioGroup v-model="access" @on-change="changeAccess">
            <Radio label="1">内网访问</Radio>
            <Radio label="2">映射访问</Radio>
            </RadioGroup>
        </FormItem>-->
        <FormItem label="内网IP" prop="ip" v-if="formValidate.type !== 2">
          <Input
            v-model.trim="formValidate.ip"
            placeholder="请输入IP"
            style="width: 300px"
            disabled
          ></Input>
        </FormItem>
        <FormItem
          label="内网服务端口"
          prop="servicePort"
          v-if="formValidate.type !== 2"
        >
          <Input
            v-model.trim="formValidate.servicePort"
            placeholder="请输入PORT(1~65535)"
            style="width: 300px"
            disabled
          ></Input>
        </FormItem>
        <FormItem label="描述" prop="description">
          <Input
            type="textarea"
            :maxlength="200"
            v-model.trim="formValidate.description"
            placeholder="描述"
          ></Input>
        </FormItem>
        <!--<FormItem  label="服务内网端口" prop="portServer">
            <Input v-model.trim="formValidate.portServer" placeholder="请输入PORT(1~65535)" style="width:300px"></Input>
        </FormItem>-->
        <!--<FormItem  label="访问跳转IP" prop="externalIp" v-if="access == '2'">
            <Input v-model.trim="formValidate.externalIp" placeholder="请输入IP"></Input>
        </FormItem>
        <FormItem  label="跳转端口" prop="externalPort" v-if="access == '2'">
            <Input v-model.trim="formValidate.externalPort" placeholder="请输入PORT(1~65535)" style="width:300px"></Input>
        </FormItem>-->
      </Form>
    </Modal>
    <Modal
      v-model="tagsModal"
      title="提示信息"
      width="800px"
      :mask-closable="false"
      footer-hide
    >
      <ctfTag
        :target="curTarget"
        v-if="tagsModal"
        :sceneInfo="sceneInfo"
      ></ctfTag>
    </Modal>
  </search-table>
</template>

<script>
    import {
        getTargetTeamList_new,
        addTargetTeam_new,
        modifyTargetTeam_new,
        delTargetTeam_new,
        getSceneInfo,
        queryVmWithParty,
        getProjectInfo,
        changeTargetVisibility
    } from '@/api/drill_compete'
    import {queryCtfList} from '@/api/question'
    import {getFlagServerList,getstatusbyprjid,queryTargetList} from '@/api/drill'
    import {getaccessgrouplist} from '@/api/access_new'
    import ctfTag from './ctfTag.vue'
    import { format } from '@/libs/utils'
	export default {
    name: 'scenes',
    props:['type','disabledAllBtn'],
   components:{ctfTag},
	data(){
		const validateNum = (rule, value, callback) => { //验证只能填入数字		    
	      	var reg = new RegExp("^([1-9]|[1-9]\\d|100)$");	     
	      	//验证警戒值		    
	      	if(value){		    	
	      		if (!reg.test(value)) {		        
	      			callback(new Error('请输入1-100的整数'));		    	
	      		}else{
	      			callback()
	      		}
	      	}else{
	      		callback()
	      	}
	      }
		const validateScore = (rule, value, callback) => { //验证只能填入数字
	      	var reg = new RegExp("^(?!0)(?:[0-9]{1,3}|1000)$");
	      	//验证警戒值
	      	if(value || value === 0){
	      		if (!reg.test(value)) {
	      			callback(new Error('请输入1-1000的整数'));
	      		}else{
	      			callback()
	      		}
	      	}else{
	      		callback()
	      	}
        }
        const validatePort = (rule, value, callback) => { //验证只能填入数字
            var reg = new RegExp("^(([1-9]\\d{0,3})|([1-5]\\d{4})|(6[0-4]\\d{3})|(65[0-4]\\d{2})|(655[0-2]\\d)|(6553[0-5]))$");
            //验证警戒值		    
            if(value){		    	
                if (!reg.test(Number(value))) {		        
                    callback(new Error('请输入1-65535的整数'));		    	
                }else{
                    callback()
                }
            }else{
                callback()
            }
        }
        const validateIP = (rule, value, callback) => { //验证只能填入数字
            var reg = new RegExp("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
            //验证警戒值	
            if(value){		    	
                if (!reg.test(value)) {		        
                    callback(new Error('ip格式错误'));		    	
                }else{
                    callback()
                }
            }else{
                callback()
            }
        }
	  	return {
            isUpdate: false,
	  	routeParams:{
            id:this.$route.query.id,
            prjid:this.$route.query.prjid
        },
        targetModal:{
        	show:false,
        	title:'',
        	loading:true,
        	type:1 //1添加，2修改
        },
        pathList:[],
//		accessGroupList:[],
//      vmlists:[],
//      teamlists:[],
		queryTargetTeamInfo:{
			pageIndex:1,
			pageSize:10,
			sceneId:this.$route.query.id,
			order:'asc',
			sortBy:'sequence'
		},
        questionList:[],
        notEnvQuestionList: [],
        access:'1',
        formValidate: {
            //"createTime": "2020-02-10T03:35:50.081Z",
            //"creator": "string",
            targetVisibility: 0,
            timer: false,
		        showTime: '',
            "description": "", //描述
            "externalIp": "", //对外ip
            "externalPort": "", //对外端口
            //"ip": "string",
            "name": "", //题目显示名称
            //"password": "string",
            "port": "",
            "projectId": this.$route.query.prjid,
            "questionId": '', //题目id
            "sceneId": this.$route.query.id,
            "score": 1,
            //"status": 0, //状态：1 正常/防护成功，2 被攻破，3 服务异常，4 被攻破+服务异常
            //"teamId": "",
            //"teamName": "",
            "type": 1, // 0：实物；1：虚拟机；2：分析靶机
            //"user": "string",
            "visibility": 0, //可见性：是否可见- 0.不可见 1可见
            //"vmId": "",
            "flagPath":"",
            "sequence":1,
            "servicePort":"",
            "isFixedFileFlag":1,
            "flag": ''
        },
        oldFormValidate:{},
        ruleValidate: {
            targetVisibility:[
					{ required: true,type:'number',message: '请选择', trigger: 'change'}
				],
            name: [
                { required: true, message: '名字不能为空', trigger: 'change' }
            ],
    //        description: [
    //          { required: true, message: '请输入描述信息', trigger: 'change' }
    //        ],
            type: [
                { required: true,type:'number',message: '请选择靶标类型', trigger: 'change' },
            ],
            score:[
                { required: true, type:'number',message: '请输入分值', trigger: 'change'},
                { validator: validateScore, trigger: 'change' }
            ],
            sequence:[
                { required: true, type:'number',message: '请输入排序', trigger: 'change'},
                { validator: validateNum, trigger: 'change' }
            ],
    //        path:[
    //          { required: true ,message: '请输入路径', trigger: 'change'}
    //        ],
    //        externalIp:[
    //        	{ required: true, message: '请输入对外IP', trigger: 'change'}
    //        ],
    //        externalPort:[
    //        	{ required: true, type:'number',message: '请输入对外端口', trigger: 'change'}
    //        ],
            questionId:[
                { required: true, message: '请选择题目', trigger: 'change'}
            ],
            flag:[
                { required: true, message: '请输入flag', trigger: 'change'}
            ],
            ip:[
                { validator: validateIP, trigger: 'change' }
            ],
            servicePort:[
                { validator: validatePort, trigger: 'change' }
            ]
    //        visibility:[
    //        	{ required: true, type:'number',message: '请选择', trigger: 'change'}
    //        ],
    //        vmId:[
    //        	{ required: true, message: '请选择虚拟机', trigger: 'change'}
    //        ],
    //        teamId:[
    //        	{ required: true, message: '请选择团队', trigger: 'change'}
    //        ],
        },
        initTargetObjData:{
            "createtime": "",
            "createuser": localStorage.getItem('username'),
            "frequency": 0,
            "id": "",
            "isshow": 1,
            "lastupdatetime": "",
            "modifier": "",
            "sceneid": "",
            "targetdes": "",
            "targetname": "",
            "targetsubmittype":0,
            "targettype": 0,
            "teamid": "",
            "type": 0,
            "uri": "",
            "vmid": "",
            "score":'1'
        },
        querytime:{},
        targetTeamCol:[
            {
                title:'题目显示名称',
                key:'name',
                align:'center',
                ellipsis:true,
                tooltip:true,
                placement:'top-left',
                width: 240
    //          width:100
            },
            {
                title: '题目类型',
                key: 'type',
                align: 'center',
                ellipsis: true,
                tooltip: true,
                width: 60,
                placement: 'top-left',
                render: (h, params) => {
                    return h('span', params.row.type != 2 ? '虚拟机靶标' : '分析靶标')
                }
            },
            {
                title:'内网IP',
                key:'ip',
                align:'center',
                ellipsis:true,
                tooltip:true,
                width:100
            },
            {
                title:'内网服务端口',
                key:'servicePort',
                align:'center',
                ellipsis:true,
                tooltip:true,
                width:60
            },
            {
                title:'路径',
                key:'flagPath',
                align:'center',
                tooltip:true,
                width:100
            },
            {
                title:'分值',
                key:'score',
                align:'center',
                ellipsis:true,
                tooltip:true,
                width:60
            },
            {
                title:'验证类型',
                key:'isFixedFileFlag',
                align:'center',
                ellipsis:true,
                tooltip:true,
                width:60,
                render:(h, params) => {
                    return h('span',this.typeFilter(params.row.isFixedFileFlag))
                }
            },
            {
                title:'Flag',
                key:'flag',
                tooltip:true,
                width:100,
                render:(h, params) => {
                    let flag = String(params.row.isFixedFileFlag) === '0' ? params.row.flag : '无'
                    return h('Tooltip',{
                        props:{
                            'max-width':'300',
                            transfer:true,
                            placement: 'top-start'
                        },
                        style:{
                            width:'100%',
                        }
                    },[
                        h('p',{
                            style:{
                                overflow: 'hidden',
                                'text-overflow': 'ellipsis'
                            }
                        }, flag),
                        h('div',{
                            slot: 'content',
                            style:{
                                'white-apace':'normal',
                                'word-break':'break-all'
                            }
                        }, flag)
                    ])
                }
            },
            {
				title: '是否显示', // 只有攻防plus需要展示定时显示时间
				key: 'targetVisibility',
				align: 'left',
				tooltip: true,
				// minWidth: 60,
				filter: (visibility)=>{
                    return visibility == 1 ? '是' : '否'
                },
				show: () => {
					return [4].includes(this.type)
				}
			},
			{
				title: '定时显示时间', // 只有攻防plus需要展示定时显示时间
				key: 'showTime',
				align: 'left',
				tooltip: true,
				// minWidth: 60,
				show: () => {
					return [4].includes(this.type)
				}
			},
            {
                title:'描述',
                key:'description',
                align:'center',
                width:100,
                tooltip:true,
            },
            {
                title:'操作',
                key:'os',
                ellipsis:true,
                width:200,
                placement:'top-right',
                key:'action',
                opList:[
                {
                    txt:'修改',
                    type:'modify',
                    disabled: () => {
                        return this.disabledAllBtn
                    },
                    fun:this.showAddAndUpdate
                },{
                    // txt: '提示' ,
                    txt: (data)=>{
                      return [4].includes(this.type) ? '提示' + `(${data.infoCount || 0})` : '提示'
                    },
                    show: () => {
                        return [4].includes(this.type);
                    },
                    disabled: () => {
                        return this.disabledAllBtn;
                    },
                    fun: (data) => {
                        this.curTarget = data;
                        this.tagsModal = true;
                    }
                }],

            }
        ],
        targetTeamData:[],
        targetTeamTotal:0,
        TargetId:'',
//      subnetList:[],
//      subnet:''
		sceneInfo:{},
		stMode:0,
		allVms:[],
		targetList:[],
        targets: [],
        curTarget: {},
	    tagsModal: false,
        errorText: '',
        showErrorText: false,
	  	}	
	},
	filters:{

	},
	computed:{
		showQuestionList(){
            if (this.formValidate.type !== 2) { // 获取需要虚拟机的题目列表
                let quesList = []
                this.targets && this.targets.forEach(item => {
                    if (item.targetType === 1) { // 靶标
                        for (let index in this.targetList) {
                            let target = Object.assign({}, this.targetList[index])
                            if (item.imageId === target.imageId) {
                                target.type = 'target';
                                target.id = target.targetId;
                                target.name = item.targetName;
                                target.key = `${target.id}-${target.name}`
                                quesList.push(target)
                                break
                            }
                        }
                    } else if (item.targetType === 2) { // 题目
                        for (let index in this.questionList) {
                            let ques = Object.assign({}, this.questionList[index])
                            if (item.targetId === ques.chaId) {
                                ques.id = ques.chaId;
                                ques.type = 'question';
                                ques.name = item.targetName
                                ques.key = `${ques.id}-${ques.name}`
                                quesList.push(ques)
                                break
                            }
                        }
                    } else {
                        // 其他类型不做处理
                    }
                })
                return quesList;
            } else { // 获取不需要虚拟机的题目列表
                return this.notEnvQuestionList.map(item => {
                    item.type = 'question';
                    return item
                })
            }
		}
	},
	mounted(){
    	//this.getAllSence()
    	//this.getAllTargetHost();
//  	this.getAccessGroupList();
    	this.getAllVmlist(true);
        getSceneInfo(this.$route.query.id).then(data => {
        	if(data.code == 1){
        		this.sceneInfo = data.data;
        		this.stMode = JSON.parse(data.data.extension).stMode;
        		if(this.stMode == 0){
        			this.targetTeamCol.splice(0, 0,{
			            title:'排序',
			            key:'sequence',
			            align: 'center',
			            ellipsis:true,
			            width:60
		            });
        		}
        	}
        });
        this.queryCtfQuestionListNotEnv()
    	this.queryCtfQuestionList();
    	this.getTargetTeamList();
    	this.queryTargetList()
	},
    methods:{
        // 判断传入的时间字符串是否在当前时间之前
		isBeforeTimestamp(dataStr) {
			return new Date(dataStr) <= new Date()
		},
        changeTime(time){
			this.showErrorText = this.isBeforeTimestamp(time)
			if (this.showErrorText) {
				this.errorText = '显示时间不得早于当前时间'
			}
		  	this.formValidate.showTime = time;
			if (!time) {
				this.showErrorText = true
				this.errorText = '请设置显示时间'
			}
		},
        // 默认一小时后展示
	    setTime(timer){
	    	this.formValidate.timer = timer;
			if (!this.formValidate.showTime) {
				let timeStr = format(new Date(new Date().getTime() + 3600000), 'yyyy-MM-dd hh:mm')
				this.formValidate.showTime = timeStr;
			}
			if (!timer) {
				this.showErrorText = timer
			}
		},
        changeType(type) {
            this.$refs.formValidate.resetFields()
            this.$nextTick(() => {
                this.$set(this.formValidate, 'type', type) // 重置表单时，type被重置了，重新设置一下type的值
                if (type === 2) {
                    this.$set(this.formValidate, 'isFixedFileFlag', '0')
                } else {
                    this.$set(this.formValidate, 'isFixedFileFlag', '')
                }
            })
        },
    	initData(){
    		this.formValidate = {
                flag: '',
                //"createTime": "2020-02-10T03:35:50.081Z",
                //"creator": "string",
                timer: false,
				        showTime: '',
                targetVisibility: 0,
                "description": "", //描述
                "externalIp": "", //对外ip
                "externalPort": "", //对外端口
                //"ip": "string",
                "name": "", //题目显示名称
                //"password": "string",
                "port": "",
                "projectId": this.$route.query.prjid,
                "questionId": '', //题目id
                "sceneId": this.$route.query.id,
                "score": 1,
                //"status": 0, //状态：1 正常/防护成功，2 被攻破，3 服务异常，4 被攻破+服务异常
    //			  "teamId": "",
    //			  "teamName": "",
                "type": 1, // 0：实物；1：虚拟机；2：分析靶机
                //"user": "string",
                "visibility": 0, //可见性：是否可见- 0.不可见 1可见
    //			  "vmId": "",
                "flagPath":"",
                "sequence":1,
                "servicePort":'',
    //			  "subnet":""
	        }
    	},
    	showAddAndUpdate(info){
    		this.initData();
//  		this.getProjectSubnet();
    		this.targetModal.show = true;
    		if(!info){
    			this.targetModal.title = '添加题目';
                this.isUpdate = false
    			this.targetModal.type = 1;
    			this.access = "1"; 
    			this.formValidate.sequence = this.targetTeamTotal + 1 ;
    		}else{
    			this.targetModal.title = '修改题目';
    			this.targetModal.type = 2;
                this.isUpdate = true
    			//this.formValidate = {};
//  			this.oldFormValidate = JSON.parse(JSON.stringify(info));
    			this.formValidate = JSON.parse(JSON.stringify(info));
                if (this.formValidate.showTime) {
					  this.$set(this.formValidate, 'timer', true)
				}else{
          this.$set(this.formValidate, 'timer', false)
        }
//  			let path
//  			if(info.targetTempInfos.filter(t => t.type == 1).length > 0){
//  				path = info.targetTempInfos.filter(t => t.type == 1)[0].info;
//  			}
//    			let portServer = info.targetTempInfos.filter(t => t.type == 3)[0].info;
//    			this.formValidate.portServer = portServer;
//  			this.formValidate.path = path;
    			this.question = {imageId:this.formValidate.imageId};
//  			this.setTeamGroup(this.formValidate.teamId);
  			    if(this.formValidate.externalPort || this.formValidate.externalIp ){
  				    this.access = "2";
  			    }else{
  				    this.access = "1";
  			    }
    		}
    	},
	  	addTargetTeam(){
	  		let params = JSON.parse(JSON.stringify(this.formValidate));
//	  		params.targetTempInfos = [];
	  		params.questionName = this.question.name;
//	  		if(this.formValidate.portServer){  //如果有路径，添加团队临时信息
//	  			params.targetTempInfos.push(
//				    {
//				      "id": "",
//				      "info": this.formValidate.portServer,
//				      "targetId": "",
//				      "type": 3  //服务内网端口
//				    }
//				)
//	  		}
//	  		if(this.formValidate.path){ //如果有路径，添加团队临时信息
//		  		params.targetTempInfos.push(
//				    {
//				      "id": '',
//				      "info": this.formValidate.path,
//				      "targetId":'',
//				      "type": 1 //flag路径
//				    }
//				)
//			}
	  		addTargetTeam_new(params).then(data => {
	  			if(data.code==1){
                  // 添加成功后清空搜索条件，回退到首页
                  this.queryTargetTeamInfo.pageIndex = 1
	  				this.getTargetTeamList();
	  				this.$Message.info('操作成功');
	  				this.handleReset('formValidate');
	  				this.targetModal.show = false;
	  			}else{
	  				this.$Message.error(data.message);
	  				this.cancelLoading('targetModal');
	  			}
	  		}).catch(error => {
	  			this.cancelLoading('targetModal');
	  		})
	  	},
	  	async modifyTargetTeam(){
	  		let params = JSON.parse(JSON.stringify(this.formValidate));
//	  		params.targetTempInfos = [];
	  		params.questionName = this.question.name;
        await changeTargetVisibility(this.$route.query.id, [{
            id: params.id,
            targetVisibility: params.targetVisibility,
          }]).then(res=>{
            if (res.code !== 1) {
              this.$Message.warning(res.message)
              return
            }
            if (params.timer && params.targetVisibility == 0 ) { // 没设置显示时间，不传递这个参数
              if (typeof this.formValidate.showTime === 'object') { // 奇怪这个参数有时就是个时间戳，需要转义一下
                params.showTime = `${format(this.formValidate.showTime, 'yyyy-MM-dd hh:mm')}:00`
              } else {
                params.showTime = `${this.formValidate.showTime}:00`
              }
            } else {
              params.showTime = ''
            }
            modifyTargetTeam_new(params).then(data => {
              if(data.code==1){
                this.getTargetTeamList();
                this.$Message.info('操作成功');
                this.handleReset('formValidate');
                this.targetModal.show = false;
              }else{
                this.$Message.error(data.message);
                this.cancelLoading('targetModal');
              }
            }).catch(error => {
              this.cancelLoading('targetModal');
            })
          }).catch(error=>{
              this.$Message.error('操作异常');
          })
//	  		let id = '';
//	  		if(this.formValidate.targetTempInfos.filter(temp => temp.type == 1).length > 0){
//	  			id = this.formValidate.targetTempInfos[0].id
//	  		}
//	  		if(this.formValidate.path){ //如果有路径，添加团队临时信息
//		  		params.targetTempInfos.push(
//				    {
//				      "id": id,
//				      "info": this.formValidate.path,
//				      "targetId":params.id,
//				      "type": 1 //flag路径
//				    }
//				)
//			}
//	  		if(this.access == "1"){
//	    		params.externalPort = '';
//    			params.externalIp = '';
//	    	}else{
//	    		params.port = '';
//	    	}
	  	},
        visibleChange(type) {
            if (!type) {
                this.$refs.formValidate.resetFields()
            }
        },
	  	saveTargetTeam(){
	  		this.$refs['formValidate'].validate((valid) => {
	            if (valid) {
                    if(!this.showErrorText){
                        if (this.formValidate.type === 2) {
                            this.formValidate.flagPath = ''
                        }
	            	    if(this.targetModal.type == 1){
	            	    	this.addTargetTeam();
	            	    }else{
	            	    	this.modifyTargetTeam();
	            	    }
                    }else{
                        this.cancelLoading('targetModal');
                    }
	            }else{
	            	this.cancelLoading('targetModal');
	            }
	        })
	  	},
	  	getTargetTeamList(){
	  		getTargetTeamList_new(this.queryTargetTeamInfo).then(data => {
	  			if(data.code==1){
	  				this.targetTeamData = data.data.items || data.data;
	  				this.targetTeamTotal = data.data.total;
	  			}else{
	  				
	  			}
	  		})
	  	},
	  	delTargetTeam(id){
	  		delTargetTeam_new(id).then(data => {
	  			if(data.code==1){
                  // 删除后展示当前页，当前页没有数据展示前一页
                  this.queryTargetTeamInfo.pageIndex = (this.targetTeamData.length == 1 && this.queryTargetTeamInfo.pageIndex > 1) ?
                          this.queryTargetTeamInfo.pageIndex - 1 : this.queryTargetTeamInfo.pageIndex;
	  				this.getTargetTeamList();
	  			}else{
	  				
	  			}
	  		})
	  	},
	  	cancelLoading(name){
	    	this[name].loading = false;
	      	setTimeout(() => {
	      		this[name].loading = true;
	      	})
	    },
	    statusFilter(val){
	      let str = '';
	      switch (val) {
	      	case 1:str = '正常/防护成功';break;
	        case 2:str = '被攻破';break;
	        case 3:str = '服务异常';break;
	        case 4:str = '被攻破+服务异常';break
	        default:break;
	      }
	      return str;
	    },
	    getAllVmlist(setAll){
	        let params = {
						page:1,
						pageSize:10000,
						sortBy:'name',
						order:'asc',
						findPorts:true,
						vmType:'TEST'
					}
//	        let params = {
//	        	page:1,
//	        	rows:10000,
//	        	sortBy:'name',
//				order:'asc',
//	        	projectId:this.routeParams.prjid,
//	        }	
	        if(this.question){
	        	params.imageId = this.question.imageId;
	        }
	        if(this.group){
	        	//params.party = this.group.partyId;
	        }
//	        params.networkId = this.formValidate.subnet;
			queryVmWithParty(this.routeParams.prjid,params).then(data => {
//		    getProjectSevers(params).then(data => {
				if(data.code == 1){
					if(setAll){
						this.allVms = data.data.list || data.data;
					}else{
						let vmlists = data.data.list || data.data;
						let vm = vmlists.filter(vm => vm.imageId == this.question.imageId);
						if(vm.length > 0){
							this.formValidate.ip = vm[0].address[0].ips[0].ipAddress;
							this.formValidate.name = vm[0].name;
						}
					}
					//this.getVmIp(this.formValidate.vmId);
//					if(this.vmlists.length > 0){
//						let server = this.vmlists.filter(vm => vm.id == this.formValidate.vmId)[0];
//	    		        if(server){
//	    		        	this.formValidate.subnet = server.addresses[0].subnetId;
//	    		        	this.getFlagServerList(server.address[0].ipv4);
//	    		        	this.getFlagServerList(server.addresses[0].ip);
//	    		        }
//					}
				}
			})
	    },
//	    getAccessGroupList(){
//			if(!this.routeParams.id){
//				return;
//			}
//			let params = {
//				pageIndex:1,
//				pageSize:2147483647,
//				testId:this.routeParams.id
//			};
//			this.selectGroupList = [];
//			getaccessgrouplist(params).then(data => {
//				if(data.code == 1){
//					this.accessGroupList = data.data.items;
//				}else if(data.code == -2) {
//					this.accessGroupList = [];
//				}else{
//					this.$Message.warning(data.message);
//				}
//			})
//		},
	    getTargetSize(size){
	      this.queryTargetTeamInfo.pageSize = size;
	      this.getTargetTeamList()
	    },
	    getTargetPage(page){
	      this.queryTargetTeamInfo.pageIndex = page;
	      this.getTargetTeamList()
	    },
	    // setTeamQuestion(res){
	    // 	if(!res){
	    // 		return
	    // 	}
        //     console.log(res)
        //     let val = res.value, label = res.label
	    // 	this.question = this.showQuestionList.filter(question => question.id == val && label.includes(question.name))[0];
	    // 	if(this.question.type == 'question'){
		//     	this.formValidate.servicePort = this.question.port;
		//     	this.formValidate.score = this.question.score;
		//     	this.formValidate.imageId = this.question.imageId;
		//     	this.formValidate.imageName = this.question.imageName;
		//     	this.formValidate.flagPath = this.question.flagPath || '/opt/flag.txt';
		//     	this.formValidate.isFixedFileFlag = this.question.isFixedFileFlag;
		//     	this.formValidate.isNeedSubmitFlag = this.question.isNeedSubmitFlag;
		//     	//this.formValidate.name = this.question.name;
		//     	this.formValidate.description = this.question.description;
		//     	this.formValidate.vmId = '';
        //         this.formValidate.flag = this.question.flag
        //         this.formValidate.name = this.question.name;
	    // 	}else if(this.question.type == 'target') {
	    // 		this.question = this.showQuestionList.filter(target => target.id == val)[0];
	    // 		this.formValidate.servicePort = this.question.openPort;
	    // 		this.formValidate.description = this.question.description;
	    // 		this.formValidate.imageId = this.question.imageId;
		//     	this.formValidate.imageName = this.question.imageName;
		//     	this.formValidate.flagPath = this.question.flagPath || '/opt/flag.txt';
		//     	this.formValidate.isNeedSubmitFlag = '1';
	    // 		this.formValidate.isFixedFileFlag = '1';
	    // 		this.formValidate.vmId = '';
	    // 	}
	    // },
//	    changeTeamGroup(val){
//	    	this.formValidate.vmId = '';
//	    	if(!val){
//	    		return
//	    	}
//	    	this.setTeamGroup(val);
//	    },
//	    setTeamGroup(val){
//	    	if(!val){
//	    		return
//	    	}
//	    	this.group =  this.accessGroupList.filter(group => group.id == val)[0];
//	    	this.formValidate.teamName = this.group.name;
//	    	this.getAllVmlist();
//	    },
//	    changeSubnet(){
//	    	this.formValidate.vmId = '';
//	    	this.getAllVmlist();
//	    },
	    handleReset (name) {
	      //this.$refs[name].resetFields();
	//    this.addTarget = false;
	        this.initData();
	        this.$refs [name].fields.forEach(function (e) {
			      if (e.fieldValue != undefined && e.fieldValue!='') {
			          e.resetField()
			      }
			})
	    },
        // 查询不需要环境的ctf题列表
        queryCtfQuestionListNotEnv() {
            let obj = {
	          pageIndex:1,
	          pageSize:2147483647,
	          isNeedEnv:'0',
              isNeedSubmitFlag: '1'
	        };
	        queryCtfList(obj).then(({ code, data, message }) => {
                if(code === 1){
                    this.notEnvQuestionList = data.items;
                }else{
                    this.$Message.warning(message);
                }
	        })
        },
	    queryCtfQuestionList(){//查询ctf题列表-不分页--需要环境
	        let obj = {
	          pageIndex:1,
	          pageSize:2147483647,
	          isNeedEnv:'1',
	          //visibility:'share',
	          //isNeedSubmitFlag:'1',
	          //category:this.autoPro.ctfType.join(',')
	        };
	        let _this = this;
	        queryCtfList(obj).then(data => {
                if(data.code == 1){
                    _this.questionList = data.data.items.filter(ques => ques.imageId) || data.data;
                    if(_this.questionList.length == 0){
                        _this.$Message.warning('该工程下没有满足要求的虚拟机');
                    }
                }else{
                    _this.$Message.warning(data.message);
                }
	        })
	    },
	    queryTargetList(){
	    	let params = {
	    		page:1,
	            rows:2147483647,
	    	};
	        queryTargetList(params).then(data => {
	          if(data.code == 1){
	            this.targetList = data.attribute.data;
	          }else{
	            this.$Message.warning(data.message);
	          }
	        })
        },
	    changeVm(id){
	    	this.formValidate.path = '';
	    	this.getVmIp(id);
	    },
	    getVmIp(id){
	    	if(id){
	    		let server = this.vmlists.filter(vm => vm.id == id)[0];
	    		this.getFlagServerList(server.address[0].ipv4);
	    		//this.getFlagServerList(server.addresses[0].ip);
	    	}
	    },
	    getFlagServerList(ip){
	    	let curIp = ip.split('.').slice(0,3).join('.');
	    	let params = {
	    		page:1,
	    		pageSize:1000,
	    		projectId:this.$route.query.prjid,
	    		ip:curIp
	    	}
	    	getFlagServerList(params).then(data => {
	    		if(data.code == 1){
	    			//this.pathList = data.data.list;
	    			if(data.data.list.lenth > 0){
	    				this.formValidate.path = data.data.list[0].addresses[0].applyFlagUrl;
	    			}
	    		}
	    	})
	    },
	    changeAccess(access){
//	    	if(access == "1" && this.targetModal.type == 2){
//	    		this.formValidate.externalPort = this.oldFormValidate.externalPort;
//    			this.formValidate.externalIp = this.oldFormValidate.externalIp;
//	    	}else if(access == "2" && this.targetModal.type == 2){
//	    		this.formValidate.port = this.oldFormValidate.port;
//	    	}
	    },
//	    getProjectSubnet(){
//	    	queryNetworkList(this.$route.query.prjid,this.projectInfo.network.id).then(data => {
//	    		if(data.code == 1){
//	    			let subnetList = [];
//	    			data.attribute.editorStage.childs.forEach(item => {
//	    				subnetList = subnetList.concat(item.childs);
//	    			})
//	    			this.subnetList = subnetList;
//	    		}
//	    	})
//	    }
		typeFilter(val){
	      let str = '未定义类型';
	      switch (val) {
	      	case '0':str = '固定Flag';break;
	        case '1':str = '静态Flag';break;
	        case '2':str = 'Checker';break;
	        case '3':str = '提交报告';break;
	        default:break;
	      }
	      return str;
	    },
  }
}
</script>

<style>
.drillsTable .ivu-poptip-body {
  text-align: left !important;
}
.scenesHeader {
  margin-bottom: 16px;
}
.drillTables {
  min-height: 300px;
}
.drillsTable.ivu-table-wrapper {
  overflow: inherit;
}
</style>
<style scoped>
.targetHeader {
  /*padding: 10px;*/
  margin: 15px 0;
}
.error-text {
  color: #ed4014;
  display: inline-block;
}
</style>
